import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/pages/test_questions/test_questions_logic.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'dart:math';

class PictureAndTextWidget extends StatefulWidget {
  final TestQuestionsLogic logic;

  const PictureAndTextWidget({
    Key? key,
    required this.logic,
  }) : super(key: key);


  @override
  State<PictureAndTextWidget> createState() => _PictureAndTextWidgetState();
}

class _PictureAndTextWidgetState extends State<PictureAndTextWidget>
    with TickerProviderStateMixin {
  int? _selectedOptionId;
  
  // 添加网格项旋转动画控制器列表
  List<AnimationController> _rotationControllers = [];
  List<Animation<double>> _rotationAnimations = [];

  // 定义颜色列表 - 从Figma设计中提取
  final List<Color> colorList = [
    const Color(0xFFFB6F7A), // 红色 - Passionate red
    const Color(0xFF5FD1E3), // 蓝色 - Peaceful blue
    const Color(0xFF3EDB7F), // 绿色 - Natural green
    const Color(0xFFFFD43B), // 黄色 - Sunshine yellow
    const Color(0xFFC17DFF), // 紫色 - Dreamlike purple
  ];

  @override
  void initState() {
    super.initState();
    
    // 初始化已选择的答案
    final questionId = widget.logic.currentQuestion?.id;
    if (questionId != null &&
        widget.logic.userAnswers.containsKey(questionId)) {
      final answers = widget.logic.userAnswers[questionId];
      if (answers != null && answers.isNotEmpty) {
        _selectedOptionId = answers.first;
      }
    }
    
    // 初始化网格项旋转动画控制器
    _initRotationControllers();
  }
  
  void _initRotationControllers() {
    final options = widget.logic.currentQuestion?.options ?? [];
    if (options.isEmpty) return;
    
    // 清除旧的控制器
    for (var controller in _rotationControllers) {
      controller.dispose();
    }
    _rotationControllers = [];
    _rotationAnimations = [];
    
    // 为每个选项创建动画控制器
    for (int i = 0; i < options.length; i++) {
      final controller = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: 800 + (i * 100)),
      );
      
      final animation = Tween<double>(begin: 0, end: 2 * pi).animate(
        CurvedAnimation(
          parent: controller,
          curve: Curves.easeInOut,
        ),
      );
      
      _rotationControllers.add(controller);
      _rotationAnimations.add(animation);
      
      // 添加动画状态监听，实现循环旋转
      controller.addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reset();
        }
      });
      
      // 延迟启动动画，错开时间
      Future.delayed(Duration(milliseconds: 200 * i), () {
        if (mounted) controller.forward();
      });
    }
  }

  @override
  void dispose() {
    // 释放所有旋转动画控制器
    for (var controller in _rotationControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final options = widget.logic.currentQuestion?.options ?? [];
    if (options.isEmpty) {
      return const Center(child: Text(''));
    }

    return ListView.builder(
      physics: const BouncingScrollPhysics(),
      padding: EdgeInsets.symmetric(horizontal: 24.w),
      itemCount: options.length,
      itemBuilder: (context, index) {
        // 循环使用颜色列表
        final color = colorList[index % colorList.length];
        final option = options[index];
        final isSelected = _selectedOptionId == option.id;
        
        // 确保动画控制器列表长度足够
        if (index < _rotationAnimations.length) {
          return AnimatedBuilder(
            animation: _rotationAnimations[index],
            builder: (context, child) {
              return Padding(
                padding: EdgeInsets.only(bottom: 12.w),
                child: Transform(
                  alignment: Alignment.center,
                  transform: Matrix4.identity()
                    ..setEntry(3, 2, 0.001) // 添加透视效果
                    ..rotateY(_rotationAnimations[index].value * 0.05), // 轻微的旋转效果
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _selectedOptionId = option.id;
                        // 保存答案
                        if (widget.logic.currentQuestion != null) {
                          int questionId = widget.logic.currentQuestion!.id!;
                          widget.logic.userAnswers[questionId] = [option.id!];
                        }
                        
                        // 点击时触发旋转动画
                        if (!_rotationControllers[index].isAnimating) {
                          _rotationControllers[index].reset();
                          _rotationControllers[index].forward();
                        }
                      });
                    },
                    child: AnimatedContainer(
                      duration: const Duration(milliseconds: 300),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12.w),
                        border: Border.all(
                          color: isSelected ? color : AppColor.colorF5F5F5,
                          width: isSelected ? 2.w : 1.w,
                        ),
                        boxShadow: isSelected ? [
                          BoxShadow(
                            color: color.withOpacity(0.2),
                            blurRadius: 12.w,
                            offset: Offset(0, 4.w),
                            spreadRadius: 2.w,
                          ),
                        ] : null,
                      ),
                      padding: EdgeInsets.all(12.w),
                      child: Stack(
                        children: [
                          // 主要内容
                          Row(
                            children: [
                              // 圆形图标
                              Container(
                                width: 40.w,
                                height: 40.w,
                                decoration: BoxDecoration(
                                  color: color,
                                  shape: BoxShape.circle,
                                ),
                                child: Center(
                                  child: _buildIconForColor(color),
                                ),
                              ),
                              12.horizontalSpace,
                              // 文本内容
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    // 标题
                                    Text(
                                      option.content?.split('\n').first ?? '',
                                      style: TextStyle(
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w900,
                                        color: color,
                                      ),
                                    ),
                                    4.verticalSpace,
                                    // 描述
                                    Text(
                                      _getDescriptionFromOption(option),
                                      style: TextStyle(
                                        fontSize: 16.sp,
                                        color: const Color(0xFF7F909E),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          
                          // 背景渐变效果 - 只在选中状态显示
                          if (isSelected)
                            Positioned(
                              right: 0,
                              top: 0,
                              bottom: 0,
                              child: Opacity(
                                opacity: 0.32,
                                child: Container(
                                  width: 100.w,
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter,
                                      colors: [
                                        color,
                                        color.withOpacity(0.0),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          );
        }
        
        // 如果动画控制器未初始化，则显示默认视图
        return Container();
      },
    );
  }
  
  // 根据颜色返回对应的图标
  Widget _buildIconForColor(Color color) {
    if (color == colorList[0]) { // 红色 - Passionate red
      return Icon(Icons.favorite_outlined, color: Colors.white, size: 24.w);
    } else if (color == colorList[1]) { // 蓝色 - Peaceful blue
      return Icon(Icons.water_drop_outlined, color: Colors.white, size: 24.w);
    } else if (color == colorList[2]) { // 绿色 - Natural green
      return Icon(Icons.eco_outlined, color: Colors.white, size: 24.w);
    } else if (color == colorList[3]) { // 黄色 - Sunshine yellow
      return Icon(Icons.wb_sunny_outlined, color: Colors.white, size: 24.w);
    } else { // 紫色 - Dreamlike purple
      return Icon(Icons.auto_awesome_outlined, color: Colors.white, size: 24.w);
    }
  }
  
  // 从选项内容中提取描述文本
  String _getDescriptionFromOption(ModelTestDetailQuestionsOptions option) {
    final contentParts = option.content?.split('\n');
    if (contentParts != null && contentParts.length > 1) {
      return contentParts.sublist(1).join('\n');
    }
    return option.dimension ?? '';
  }
} 